from stark.service.v1 import StarkHandler, get_choice_text, get_m2m_text, StarkModelForm, SearchGroupOption
from web import models
from django.urls import re_path,reverse
from django.utils.safestring import mark_safe
from  .base import PermissionHandler

class StudentModelForm(StarkModelForm):
    """自定能够编辑的字段"""

    class Meta:
        model = models.Student
        fields = ['qq', 'mobile', 'emergency_contract', 'memo']


class StudentHandler(PermissionHandler,StarkHandler):
    model_form_class = StudentModelForm
    search_list = ['customer__name__contains', 'qq']  # 关键字搜索条件
    search_group = [
        SearchGroupOption('class_list', text_func=lambda x: '%s-%s' % (x.school.title, x))
    ]

    def display_score(self, obj=None, is_header=None):
        if is_header:
            return '积分管理'
        url = reverse('stark:web_scorerecord_list', kwargs={'student_id': obj.pk})
        return mark_safe('<a target="_blank" href="%s">%s</a>'%(url,obj.score))

    field_name_list = ['customer', 'qq', 'emergency_contract',
                       get_m2m_text('已报班级', 'class_list'),display_score,
                       get_choice_text('学员状态', 'student_status'),
                       ]

    def get_add_btn(self, request, *args, **kwargs):
        return None

    def get_field_name_list(self,request,*args,**kwargs):
        value = []
        if self.field_name_list:
            value.extend(self.field_name_list)
            value.append(type(self).display_edit)  # 添加默认显示的操作字段： 编辑和删除
        return value

    def get_urls(self):
        patterns = [
            re_path('list/', self.wrapper(self.changelist_view), name=self.get_list_url_name),
            re_path('edit/(?P<pk>\d+)', self.wrapper(self.edit_view), name=self.get_edit_url_name, )
        ]
        patterns.extend(self.extra_urls())  # 新增的url 扩增
        return patterns
